{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block styles %}
    {{ super() }}
    <link href="/static/css/bootstrap-treeview.min.css" rel="stylesheet"/>
    <style>
        .loading {
            text-align: center;
            width: 80px;
            height: 40px;
            margin: 0 auto;
        }


        .loading span {
            margin: 0 auto;
            display: inline-block;
            width: 8px;
            height: 100%;
            border-radius: 4px;
            background: lightgreen;
            -webkit-animation: load 1s ease infinite;
        }

        @-webkit-keyframes load {
            0%, 100% {
                height: 40px;
                background: lightgreen;
            }
            50% {
                height: 70px;
                margin: -15px 0;
                background: lightblue;
            }
        }

        .loading span:nth-child(2) {
            -webkit-animation-delay: 0.2s;
        }

        .loading span:nth-child(3) {
            -webkit-animation-delay: 0.4s;
        }

        .loading span:nth-child(4) {
            -webkit-animation-delay: 0.6s;
        }

        .loading span:nth-child(5) {
            -webkit-animation-delay: 0.8s;
        }
    </style>
{% endblock %}
{% block page_content %}
    <div class="loading" id="loadingDiv">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
    <div class="alert" role="alert" id="msgAlert">

    </div>
    <div class="well row">
        <div class="col-md-3">
            <div class="row" style="max-height: 800px">
                <h4>CataLogs</h4>
                <div id="catalogBtns">
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addCatalog">Add
                        CataLog
                    </button>
                    <button type="button" id="removeCatalogBtn" class="btn btn-primary">Del
                        CataLog
                    </button>
                </div>
                <div id="tree" style="margin-top: 20px;max-height: 600px;overflow-y :scroll;"></div>
            </div>
        </div>
        <div class="col-md-9">
            <h4>Query</h4>
            <div id="chartBtns" style="float:left;margin-bottom:20px;">
                <button type="button" id="chartBtn" class="btn btn-primary">ChartView
                </button>
                <button type="button" id="wranglingBtn" class="btn btn-primary">WrangLing
                </button>
            </div>
            <div id="queryBtns" style="float:right;margin-bottom:20px;">
                <div class="btn-group">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"
                            aria-haspopup="true" aria-expanded="false">
                        Saved SQL <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" id="savedsql">
                        {% for saved_sql in saved_sqls %}
                            <li style="padding:2px 8px">{{ saved_sql.sql }}</li>
                            <li role="separator" class="divider"></li>
                        {% endfor %}
                    </ul>
                </div>
                <button type="button" id="saveSqlBtn" class="btn btn-primary">Save
                </button>
                <button type="button" id="querySqlBtn" class="btn btn-primary" data-loading-text="Querying...">Query
                </button>
            </div>
            <div id="editor" style="min-height:200px;width:100%;margin-top:10px"></div>
            <div id="queryTable" style="margin-top:20px;background-color: white">
            </div>
            <div>
                <ul class="pager">
                    <li><a href="#" id="previous">&laquo;上一页</a></li>
                    <li><a href="#" id="next">下一页&raquo;</a></li>
                </ul>

            </div>
        </div>
    </div>
    <div class="modal fade" id="addCatalog" tabindex="-1" role="dialog" aria-labelledby="addCatalogLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="addCatalogLabel">Add CataLog</h4>
                </div>
                <div class="modal-body">
                    <form action="" id="addCatalogFrom">
                        <div class="input-group" style="width:100%">
                            <label for="catalog">Catalog Name:</label>
                            <input type="text" name="catalogName" class="form-control" id="catalog">
                        </div>
                        <div class="input-group" style="width:100%">
                            <label for="connecter">Connecter Name:</label>
                            <input type="text" name="connectorName" class="form-control" id="connecter">
                        </div>
                        <div class="input-group">
                            <label for="connecter">Is Public:</label>
                            <input type="checkbox" name="isPublic" style='margin:10px' id="public">
                        </div>
                        <label for="connecter">Properties:</label>
                        <dev id="propertiesGroup">

                        </dev>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" id="catalogAddBtn" class="btn btn-primary">添加</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {{ super() }}

    <script src="/static/js/bootstrap-treeview.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript"
            charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ext-language_tools.js" type="text/javascript"
            charset="utf-8"></script>
    <script>
        $(function () {
            $('#loadingDiv').hide();
            $("#next").hide();
            $("#previous").hide();
            $.fn.initInputGroup = function (options) {
                var c = $.extend({
                    widget: 'input',
                    add: "<span class=\"glyphicon glyphicon-plus\"></span>",
                    del: "<span class=\"glyphicon glyphicon-minus\"></span>",
                    field: '',
                    data: []
                }, options);

                var _this = $(this);
                addInputGroup(1);

                function addInputGroup(order) {
                    var inputGroup = $("<div class='input-group' style='margin: 5px 0'></div>");
                    var inputGroupNameAddon = $("<span class='input-group-addon'>Name</span>");
                    var inputGroupValueAddon = $("<span class='input-group-addon'>Value</span>");
                    var nameWidget, valueWidget;
                    nameWidget = $("<input class='form-control' type='text'/>");
                    valueWidget = $("<input class='form-control' type='text'/>");
                    if (c.data[order - 1]) {
                        nameWidget.val(c.data[order - 1]["name"]);
                        valueWidget.val(c.data[order - 1]["value"]);
                    }
                    var inputGroupBtnAddon = $("<span class='input-group-btn'></span>");
                    if (c.field.length == 0) {
                        nameWidget.prop('name', c.widget + 'Data[]');
                        valueWidget.prop('name', c.widget + 'Data[]');
                    } else {
                        nameWidget.prop('name', 'name[]');
                        valueWidget.prop('name', 'value[]');
                    }
                    var addBtn = $("<button class='btn btn-default' type='button'>" + c.add + "</button>");
                    addBtn.appendTo(inputGroupBtnAddon).on('click', function () {
                        if ($(this).html() == c.del) {
                            $(this).parents('.input-group').remove();
                        } else if ($(this).html() == c.add) {
                            $(this).html(c.del);
                            addInputGroup(order + 1);
                        }
                    });

                    inputGroup.append(inputGroupNameAddon).append(nameWidget).append(inputGroupValueAddon).append(valueWidget).append(inputGroupBtnAddon);
                    _this.append(inputGroup);
                    if (order + 1 > c.data.length) {
                        return;
                    }
                    addBtn.trigger('click');
                }

            };
            $('#propertiesGroup').initInputGroup({
                'widget': 'input',
                'field': 'data',
                'data': []
            });
            var data = {{ catalogs|tojson }};
            var index = 1;
            var sql = "";
            $('#tree').treeview({
                data: data,
                levels: 1,
                showTags: true,
                loadingIcon: "fa fa-hourglass",
                lazyLoad: loaddata
            });
            $("#removeCatalogBtn").click(function () {
                arr = $('#tree').treeview('getSelected');
                if (arr.length == 0) {
                    alert("请先选中catalog！");
                    return;
                }
                var ids = "";
                for (var i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        ids = arr[i].id;
                    } else {
                        ids = ids + "," + arr[i].id;
                    }
                }
                if (confirm("确定删除吗？一旦删除将无法恢复！")) {
                    $.ajax({
                        type: "delete",
                        url: "/query/catalog",
                        data: {ids: ids},
                        success: function (data) {
                            $('#tree').treeview('removeNode', [arr, {silent: true}]);
                        }
                    });
                }
            });

            $("#catalogAddBtn").click(function () {
                $.ajax({
                    type: "post",
                    url: "/query/catalog",
                    data: $("#addCatalogFrom").serialize(),
                    success: function (data) {
                        $("#addCatalog").modal('hide');
                        $("#msgAlert").removeClass('alert-danger').addClass('alert-success');
                        var innerHTML = "<strong>Add Catalog Success!</strong>";
                        $("#msgAlert")[0].innerHTML = innerHTML;
                        $("#msgAlert").fadeTo(2000, 500).slideUp(500, function () {
                            $("#msgAlert").hide();
                        });
                        $("#tree").treeview("addNode", [data.data]);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#msgAlert").removeClass('alert-success').addClass('alert-danger');
                        var innerHTML = "<strong>Add Catalog  Failed!</strong>";
                        $("#msgAlert")[0].innerHTML = innerHTML;
                        $("#msgAlert").fadeTo(2000, 500).slideUp(500, function () {
                            $("#msgAlert").hide();
                        });
                    }
                });
            });

            var editor = ace.edit("editor");
            theme = "clouds";
            editor.setTheme("ace/theme/" + theme);
            editor.setFontSize(18);
            editor.setReadOnly(false);
            editor.setOption("wrap", "free")
            ace.require("ace/ext/language_tools");
            editor.setOptions({
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });
            language = "sql";
            editor.session.setMode("ace/mode/" + language);
            var setCompleteData = function (data) {
                var langTools = ace.require("ace/ext/language_tools");
                langTools.addCompleter({
                    getCompletions: function (editor, session, pos, prefix, callback) {
                        if (prefix.length === 0) {
                            return callback(null, []);
                        } else {
                            return callback(null, data);
                        }
                    }
                });
            };
            updateCompleteData();
            $("#saveSqlBtn").click(function () {
                $.ajax({
                    type: "post",
                    url: "/query/history",
                    data: {'sql': editor.getValue()},
                    success: function (data) {
                    }
                });
            });
            $("#savedsql li").click(function () {
                editor.setValue($(this).text(), 1);
                editor[0].focus();
            });

            $("#querySqlBtn").click(function () {
                var btn = $(this);
                btn.button('loading');
                $('#loadingDiv').modal('show');
                $.ajax({
                    type: "post",
                    url: "/query/sql",
                    data: {'sql': editor.getValue(), 'index': 1},
                    success: function (data) {
                        $('#queryTable').empty();
                        $('#queryTable').append(data.data);
                        btn.button('reset');
                        index = data.index;
                        sql = data.sql;
                        $("#next").show();
                        $("#previous").show();
                        $('#loadingDiv').modal('hide');
                    }
                });
            });
            $("#next").click(function () {
                $.ajax({
                    type: "post",
                    url: "/query/sql",
                    data: {'sql': sql, 'index': index + 1},
                    success: function (data) {
                        $('#queryTable').empty();
                        $('#queryTable').append(data.data);
                        index = data.index;
                    }
                });
            });
            $("#previous").click(function () {
                $.ajax({
                    type: "post",
                    url: "/query/sql",
                    data: {'sql': sql, 'index': index - 1},
                    success: function (data) {
                        $('#queryTable').empty();
                        $('#queryTable').append(data.data);
                        index = data.index;
                    }
                });
            });

            $("#chartBtn").click(function () {
                window.location.href = '/query/chart?sql=' + sql + '&is_wrangling=false';
            });
            $("#wranglingBtn").click(function () {
                window.location.href = '/query/wrangling?sql=' + sql;
            });

        });
        function loaddata(node, func) {
            $('#loadingDiv').modal('show');
            $.getJSON("/query/treeview", {type: node.type, param: node.param}, function (json) {
                func(json.data);
                updateCompleteData();
                $('#loadingDiv').modal('hide')
            });
        }
        function updateCompleteData() {
            var nodes = $('#tree').treeview('getNodes');
            var completeData = [];
            $.each(nodes, function (index, obj) {
                completeData.push({'meta': obj.type, 'caption': obj.text, 'value': obj.text, 'score': 1})
            });
            setCompleteData(completeData);
        }
        function setCompleteData(data) {
            var langTools = ace.require("ace/ext/language_tools");
            langTools.addCompleter({
                getCompletions: function (editor, session, pos, prefix, callback) {
                    if (prefix.length === 0) {
                        return callback(null, []);
                    } else {
                        return callback(null, data);
                    }
                }
            });
        }
    </script>
{% endblock %}
